﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using LetsTestAPI.EDM;
using Newtonsoft.Json.Linq;
using LetsTestAPI.Models;

namespace LetsTestAPI.Controllers
{
    public class MTTController : ApiController
    {
        public string GetListOfTests()
        {
            using (LetsTestEntities context = new LetsTestEntities())
            {
                List<TestModel> models = new List<TestModel>();
                List<Test> tests = context.Tests.Where(t => t.IsActive == true).ToList();
                foreach(Test t in tests)
                {
                    models.Add(new TestModel(t.Name, t.Time));
                }
                JArray job = JArray.FromObject(models);
                return job.ToString();
            }
        }


        public string GetTest(int TestID)
        {
            using (LetsTestEntities context = new LetsTestEntities())
            {
                Test test = context.Tests.Where(t => t.Id == TestID).FirstOrDefault();
                TestModel model = new TestModel(test.Name, test.Time);
                JObject job = JObject.FromObject(model);
                return job.ToString();
            }
        }

        [HttpPost]
        public void AddOrEditTest([FromBody]JObject jsonData)
        {
            string Name = String.Empty;
            int TestID = 0;
            int Time = 0;
            string IsActive = String.Empty;
            if (jsonData["Name"] != null) { Name = jsonData["Name"].ToString(); }
            if (jsonData["TestID"] != null) TestID = Int32.Parse(jsonData["TestID"].ToString());
            if (jsonData["Time"] != null) Time = Int32.Parse(jsonData["Time"].ToString());
            if (jsonData["IsActive"] != null) IsActive = jsonData["IsActive"].ToString();

            using (LetsTestEntities context = new LetsTestEntities())
            {
                if (TestID != 0)
                {
                    var rows = context.Tests.Where(t => t.Id == TestID);
                    if (rows != null)
                    {
                        var row = rows.FirstOrDefault();
                        if (!String.IsNullOrEmpty(Name)) row.Name = Name;
                        if (Time != 0) row.Time = Time;
                        if (!String.IsNullOrEmpty(IsActive)) row.IsActive = Boolean.Parse(IsActive);
                        context.SaveChanges();
                    }
                }
                else
                {
                    context.Tests.Add(new Test { Name = Name, IsActive = true, SpecialistID = 1, Time = Time });
                    context.SaveChanges();
                }
            }


        }
    }
}
